import Strings from '@/i18n';
import { useProps, useDpSchema } from '@ray-js/panel-sdk';
import { ToastInstance } from '@ray-js/smart-ui';
import { useEffect, useState } from 'react';

const getBitValue = (num, idx) => (num & (1 << idx)) >> idx;

export const useFault = () => {
  const [msg, setMsg] = useState<string[]>([]);

  const { fault } = useProps();
  const schema = useDpSchema();

  const getFaultStrings = (faultValue: number) => {
    if (!faultValue) return [];
    console.log(`🚀 ~ schema:`, schema);

    const label = schema?.fault?.property.label || [];
    const labels: string[] = [];
    for (let i = 0; i < label.length; i++) {
      const value = label[i];
      const isExist = getBitValue(faultValue, i);
      if (isExist) {
        labels.push(Strings.getLang(value));
      }
    }
    return labels;
  };

  useEffect(() => {
    const txt = getFaultStrings(fault);

    if (txt.length > 0) {
      ToastInstance({
        message: txt.join('，'),
        position: 'top',
        duration: 5000,
      });
    } else {
      ToastInstance.clear;
    }
  }, [fault]);

  return msg;
};
